package com.ct.web.common.interceptors;

import org.springframework.web.context.request.WebRequestInterceptor;
import org.springframework.web.context.request.WebRequest;
import org.springframework.ui.ModelMap;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.logging.Log;
import org.hibernate.SessionFactory;
import org.hibernate.Session;


/**
 * Created by IntelliJ IDEA.
 * User: nmkravchenko
 * Date: 23.10.2009
 * Time: 15:14:48
 * To change this template use File | Settings | File Templates.
 */
public class OpenSessionInViewInterceptor implements WebRequestInterceptor{
    private static Log log = LogFactory.getLog(OpenSessionInViewInterceptor.class);
    private SessionFactory sessionFactory;

    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    public void preHandle(WebRequest webRequest) throws Exception {
        log.debug("Creating a hibernate transaction ...");
        Session session = sessionFactory.getCurrentSession();
        session.beginTransaction();
    }

    public void postHandle(WebRequest webRequest, ModelMap modelMap) throws Exception {

    }

    public void afterCompletion(WebRequest webRequest, Exception e) throws Exception {
        log.debug("Finishing a hibernate transaction ...");
        try{
            sessionFactory.getCurrentSession().flush();
            sessionFactory.getCurrentSession().getTransaction().commit();
        }catch(Exception ex){
            log.error(e);
            sessionFactory.getCurrentSession().getTransaction().rollback();
        }
        
    }
}
